package org.vacoor.nothing.security.tags;

import org.vacoor.nothing.common.reflect.Mates;

import java.util.*;

/**
 * @author vacoor
 */
public abstract class Functions {

    public static String appendParam(Map<String, String[]> params, String p, Object v) {
        v = null == v ? "" : v;
        Map<String, String[]> clone = new HashMap<String, String[]>(params);

        String[] newValues = clone.get(p);
        newValues = null == newValues ? new String[1] : Arrays.copyOf(newValues, newValues.length + 1);
        newValues[newValues.length - 1] = String.valueOf(v);

        clone.put(p, newValues);
        return toQs(clone);
    }

    public static String removeParam(Map<String, String[]> params, String p) {
        Map<String, String[]> clone = new HashMap<String, String[]>(params);
        clone.remove(p);
        return toQs(clone);
    }

    public static String removeParamValue(Map<String, String[]> params, String p, String v) {
        Map<String, String[]> clone = new HashMap<String, String[]>(params);
        String[] values = clone.get(p);
        List<String> newValues = new ArrayList<String>();

        if (null != values) {
            for (String value : values) {
                if (v == value || (null != v && v.equals(value))) {
                    continue;
                }
                newValues.add(value);
            }
            clone.put(p, newValues.toArray(new String[newValues.size()]));
        }
        return toQs(clone);
    }

    public static String replaceParam(Map<String, String[]> params, String p, String value) {
        Map<String, String[]> clone = new HashMap<String, String[]>(params);
        clone.put(p, new String[]{value});
        return toQs(clone);
    }

    public static String toQs(Map<String, String[]> params) {
        StringBuilder buff = new StringBuilder();
        for (Map.Entry<String, String[]> param : params.entrySet()) {
            String key = param.getKey();
            String[] values = param.getValue();

            for (String value : values) {
                buff.append("&").append(key).append("=").append(value);
            }
        }
        return buff.replace(0, 1, "?").toString();
    }

    public static boolean contains(Iterable<?> it, Object target) {
        if (null == it) {
            return false;
        }
        for (Object e : it) {
            if (e == target || (e != null && e.equals(target))) {
                return true;
            }
        }
        return false;
    }

    public static boolean hasEqPropObj(Iterable<?> it, Object target, String prop) {
        if (null == it || null == target) {
            return false;
        }
        Object value = Mates.from(target).get(prop);
        for (Object el : it) {
            if (null != el && value.equals(Mates.from(el).get(prop))) {
                return true;
            }
        }
        return false;
    }

}
